<template>
  <view class="set-scenario">
    <view class="section-box">
      <view class="section-content">
        <view class="item-line">
          <view class="line-field">
            <view class="label">
              <text>当前使用场景：</text>
            </view>
            <view class="content">
              <uni-data-select
                  class="scene-select"
                  v-model="currentScene"
                  :localdata="sceneList"
                  :clear="false"
              ></uni-data-select>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="section-box">
      <view class="section-title"><view class="title">灯具参数</view></view>
      <view class="section-content">
        <view class="item-line" v-for="item in currSceneParams" :key="item.key">
          <view class="line-field">
            <view class="label">
              <text>{{item.label}}</text>
            </view>
            <view class="content">
              {{ item.valueText }}
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="section-box">
      <view class="section-title">
        <view class="title">单灯设置</view>
        <switch :checked="enableSingleLampSetting" @change="switchSingleControl()" />
      </view>
      <view v-if="enableSingleLampSetting" class="section-content">
        <view class="item-line">
          <view class="line-field">
            <view class="label">
              <text>灯具编码</text>
            </view>
            <view class="operate">
              <input placeholder="请输入灯具编码" v-model="targetLampId" />
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="page-bottom-btn" @click="saveSetting()">确定</view>
  </view>
</template>

<script>
import mixin from '@/mixins/index.js'
import { USER_ROLE } from '@/constant/index.js'
import { getGUID } from '@/utils/index.js'
export default {
  mixins: [mixin],
  data() {
    return {
      currentScene: '',
      sceneMap: {},
      sceneList: [],
      paramList: [],
      enableSingleLampSetting: false,
      targetLampId: '',
      currSceneParams: []
    }
  },
  watch: {
    currentScene() {
      this.initParams()
    }
  },
  mounted() {
    this.getProjectInfo()
    this.getParamList()
    this.getProjectScene()
  },
  methods: {
    initParams() {
      const sceneObj = this.sceneMap[this.currentScene]
      if (!sceneObj || !this.paramList.length) return []
      this.currSceneParams = Array.from(
          this.paramList.filter(
              (item) => {
                if (sceneObj?.type !== 3 && item.name === 'middle_light') {
                  return false;
                }
                return !item.hidden;
              },
          ),
          (item) => {
            const currentValue = sceneObj?.paramObj[item.name] ?? item.value
            const paramItem = {
              key: item.key,
              label: item.label,
              valueText: currentValue,
            };
            if (item.type === 'selector') {
              paramItem.valueText = item.nameMap[currentValue];
            }
            return paramItem;
          },
      );
    },
    getProjectInfo() {
      const self = this
      uni.request({
        url: '/project/get',
        data: {
          id: self.params.projectId
        },
        success(result) {
          if (result.data.success && result.data.data) {
            const projectInfo = result.data.data
            projectInfo.name = projectInfo.name || ''
            projectInfo.isOwner = projectInfo.user_id === self.userInfo?.id
            projectInfo.canEdit = projectInfo.isOwner || self.canEdit
            self.currentScene = projectInfo.scene
            uni.setNavigationBarTitle({
              title: projectInfo.name
            })
            self.initParams()
          }
        }
      })
    },
    getProjectScene() {
      const self = this
      self.sceneMap = {}
      self.sceneList = []
      uni.request({
        url: '/project_scene/list',
        data: {
          xm_id: this.params.projectId
        },
        success(result) {
          if (result.data.success && Array.isArray(result.data.data)) {
            const arr = []
            result.data.data.forEach(item => {
              const sceneItem = {
                key: item.id,
                id: item.id,
                name: item.name || '',
                text: item.name || '',
                value: item.id,
                type: item.type,
                paramObj: {}
              }
              if (item.param) {
                try {
                  sceneItem.paramObj = JSON.parse(item.param)
                } catch (e) {
                  console.error(e)
                }
              }
              self.sceneMap[sceneItem.id] = sceneItem
              arr.push(sceneItem)
            })
            self.sceneList = arr
            self.initParams()
          }
        }
      })
    },
    getParamList() {
      const self = this
      self.paramMap = {}
      self.paramList = []
      uni.request({
        url: '/sys/fieldsn',
        method: 'GET',
        success(result) {
          if (result.data.success && Array.isArray(result.data.data)) {
            const arr = []
            result.data.data.forEach((item) => {
              if (!item) return
              const { label = '', name, value, type, step = 1, min = 0, max = 100, desc, range = [], user = 1 } = item
              range.forEach((option) => {
                option.text = option.name || ''
              })
              const paramItem = {
                key: getGUID(),
                label,
                name,
                value,
                type,
                step,
                min,
                max,
                desc,
                range,
                hidden: user === 1 ? false : self.userInfo.role !== USER_ROLE.ADMIN,
                nameMap: {}
              }
              paramItem.range.forEach((option) => {
                option.text = option.name || ''
                paramItem.nameMap[option.value] = option.name
              });
              self.paramMap[name] = paramItem;
              arr.push(paramItem)
            })
            self.paramList = arr
            self.initParams()
          }
        }
      })
    },
    switchSingleControl() {
      const self = this
      self.enableSingleLampSetting = !self.enableSingleLampSetting
      self.targetLampId = ''
    },
    saveSetting() {
      const self = this
      uni.request({
        url: '/project/modify',
        method: 'POST',
        data: {
          id: self.params.projectId,
          scene: self.currentScene,
        },
        success(result) {
          if (result.data.success) {
            uni.showToast({
              icon: 'none',
              title: '保存成功'
            })
            self.goBack()
          }
        }
      })
    },
    goBack() {
      uni.navigateBack();
    }
  }
}
</script>

<style lang="scss" scoped>
.set-scenario {
  padding: 30rpx 30rpx 140rpx;
}
.section-box {
  padding: 30rpx;
  background-color: $white;
  border-radius: 10rpx;
  margin-top: 40rpx;
  &:first-child {
    margin-top: 0;
  }
}
.section-title {
  @include section-title;
  & + .section-content {
    margin-top: 30rpx;
  }
}
.item-line {
  margin-top: 30rpx;
  &:first-child {
    margin-top: 0;
  }
  .line-field {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .content {
      text-align: right;
      width: 240rpx;
    }
  }
  .label {
    font-size: $font-size-3;
    vertical-align: baseline;
    .info {
      font-size: $font-size-0;
      color: $text-secondary;
    }
  }
}
</style>
